package com.tzh.utils;

import com.github.pagehelper.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 用于将数据库对象转为接口对象
 *
 * @author Administrator
 */
public class ServiceUtils<T> {


    private static final Logger log = LoggerFactory.getLogger(ServiceUtils.class);

    public static <T> Page<T> getPageList(Page<?> list, Class<T> clazz) {
        Page<T> page = new Page<T>();
        List<T> retList = new ArrayList<T>();
        list.stream().forEach(eo -> {
            T dto;
            try {
                dto = newTclass(clazz);
                BeanUtils.copyProperties(eo, dto);
                retList.add(dto);
            } catch (Exception e) {
                log.error("对象转换失败：{}", e.getMessage());
            }
        });

        page.setTotal(list.getTotal());
        page.setPages(list.getPages());
        page.addAll(retList);
        page.setPageNum(list.getPageNum());
        page.setPageSize(list.getPageSize());
        return page;
    }


    private static <T> T newTclass(Class<T> clazz) throws InstantiationException, IllegalAccessException {
        T a = clazz.newInstance();
        return a;

    }
}
